import dbl from "@/utils/dbl";
import { logout } from "@/api/login";
import router from '@/router'
const user = {
	state: {
		user: {},
		roles: {},
		menus: [],
		loadMenus: false,
		needResetPassword: false // 是否需要重置密码
	},

	mutations: {
		SET_USER: (state, userInfo) => {
			state.user = userInfo;
		},
		SET_ROLES: (state, roles) => {
			let data = {};
			roles.forEach(item => {
				data[item] = true;
			});
			state.roles = data;
		},
		SET_MENU: (state, menus) => {
			state.menus = menus;
		},
		// 是否需要重设密码
		SET_RESET_PASSWORD (state, value) {
			state.needResetPassword = value;
		}
	},

	actions: {
		// 登出
		LogOut ({ commit }) {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					let lastUrl = localStorage.getItem("lastUrl");
					if (lastUrl) {
						localStorage.clear();
						localStorage.setItem("lastUrl", lastUrl);
					} else {
						localStorage.clear();
					}
					router.replace({
						path: '/login'
					})
				});
			});
		},
		initUser ({ commit }) {
			let menus = dbl.get("menus");
			let user = dbl.get("user");
			let roles = dbl.get("roles");
			let needResetPassword = dbl.get("needResetPassword");
			if (menus && user && roles) {
				commit("SET_USER", user);
				commit("SET_ROLES", roles);
				commit("SET_MENU", menus);
				commit("SET_RESET_PASSWORD", needResetPassword);
			}
		}
	}
};

export default user;
